<?php

/* @project : Template
 * @auther  : 青云
 * @date    : 2018/1/10
 * @desc    : 系统设置模型
 */

namespace app\common\model;

use think\Model;
use think\Request;

class SystemConfig extends Model
{
    public function getFieldListByTabId($tab_id)
    {
        $where[] = ['config_tab_id', 'eq', $tab_id];
        $where[] = ['is_del', 'eq', 0];
        $where[] = ['is_valid', 'eq', 1];

        $field = 'name field_name,code field_code,field_type,field_param,val';

        $list = $this->where($where)->field($field)->select();

        return $list;
    }

    public static function getValByCode($code)
    {
        return self::get(['code' => $code])['val'];
    }

    public function getListByDataType($data_type)
    {
        $where[] = ['data_type', 'eq', $data_type];
        $list = $this->where($where)->column('code,val');

        return $list;
    }

    public function setSystemConfig(Request $request)
    {
        $data_type = $request->data_type;
        $data = $request->param();

        foreach ($data as $key => $val) {
            if (strpos($data_type . '_', $key) == 0) {
                $this->set_val($key, $val, $data_type);
            }
        }

        return true;
    }

    public function set_val($key, $val, $data_type)
    {
        $data['val'] = $val;
        $data['data_type'] = $data_type;
        $where_system[] = array('code', 'eq', $key);
        $vo = model('SystemConfig')->where($where_system)->find();

        if ($vo) {
            $data['id'] = $vo['id'];
            $list = $vo->data($data)->save();
        } else {
            $data['code'] = $key;
            $list = model('SystemConfig')->insert($data);
        }
    }
}
